from flask import Blueprint,request,jsonify
import json
from models.user import *
from util.myredis import r
# 导入雪花算法
import snowflake.client

classidy_blue = Blueprint("classidyblue",__name__)

# @classidy_blue.route("/getmenu")
# def getmenu():
#     classify = db.session.execute("select * from classify where pid=0")
#     # type = classify.query.filter_by(pid=0).all()
#     # type = list(type)
#     # print(type)
#     clist = list(classify)
#
#     print(clist)
#     list1 = []
#     for i in list1:
#         list1.append({'id': i[0], 'name': i[3]})
#     return jsonify({'code': 200, 'data': list1})

@classidy_blue.route("/getone")
def getone():
    classify = db.session.execute("select * from classify")
    print('________',classify)
    clist = list(classify)
    print("*****", clist)
    list1 = []
    menulist = []
    # 获取到一级分类
    for i in clist:
        if i[4] == 0:
            if i[4] not in menulist:
                list1.append({'id': i[0], 'name': i[3], 'children': []})
                menulist.append([i[0]])
    print(list1)
    # 获取到每个一级分类下的二级分类
    for j in clist:
        for index,p in enumerate(list1):
            if j[4] == p['id']:
                list1[index]['children'].append({'id': j[0], 'name': j[3],'pid':j[4],'children1':[]})
    print('______',list1)

    for x in clist:
        for index,p in enumerate(list1):
            aa = list1[index]['children']
            for index,t in enumerate(aa):
                if x[4] == t['id']:
                    aa[index]['chlidren'].append({'id': x[4], 'name': x[3]})
            # print('___***___', aa)
    return jsonify({'code': 200, 'data': list1})

@classidy_blue.route("/setbasic", methods=['POST'])
def setbasic():
    data = request.data
    if data:
        data = json.loads(data)
        userid = data['userid']
        name = data['name']
        sex = data['sex']
        identity = data['identity']
        addr = data['addr']
        email = data['email']
        bas = basic.query.filter_by(userid=userid).first()
        if bas:
            bas.name = name
            bas.sex = sex
            bas.identity = identity
            bas.addr = addr
            bas.email = email
            db.session.add(bas)
            db.session.commit()
            return jsonify({'code': 200, 'msg': '修改成功'})
        bsc = basic(name=name,sex=sex,identity=identity,addr=addr,email=email,userid=userid)
        db.session.add(bsc)
        db.session.commit()
        return jsonify({'code': 200, 'msg': 'ok'})
    else:
        return jsonify({'code': 300, 'msg': '输入信息'})

# 查找当前用户信息是否存在
@classidy_blue.route("/getbasic")
def getbasic():
    userid = request.args.get('userid')
    print(userid)
    bas = basic.query.filter_by(userid=userid).first()
    print(bas)
    list = []
    list.append({'id': bas.id, 'name': bas.name, 'sex': bas.sex, 'identity': bas.identity, 'addr': bas.addr,
                 'email': bas.email})
    print(list)
    return jsonify({'code': 200, 'list': list})


@classidy_blue.route("/setserve", methods=['POST'])
def setserve():
    data = request.data
    if data:
        data = json.loads(data)
        userid = data['userid']
        ability = data['ability']
        skil = data['skil']
        pay = data['pay']
        close = data['close']
        work = data['work']
        worktime = data['worktime']
        bas = serve.query.filter_by(userid=userid).first()
        if bas:
            bas.ability = ability
            bas.skil = skil
            bas.pay = pay
            bas.close = close
            bas.work = work
            bas.worktime = worktime
            db.session.add(bas)
            db.session.commit()
            return jsonify({'code': 200, 'msg': '修改成功'})
        bas = serve(ability=ability, skil=skil, pay=pay, close=close, work=work, worktime=worktime)
        db.session.add(bas)
        db.session.commt()
        return jsonify({'code': 200, 'msg': 'ok'})
    else:
        return jsonify({'code': 200, 'msg': '请输入信息'})

# 查找当前用户是否存在
@classidy_blue.route("/getserve")
def getserve():
    userid = request.args.get('userid')
    bas = serve.query.filter_by(userid=userid).first()
    list = []
    list.append({'id': bas.id, 'ability': bas.ability, 'skil': bas.skil, 'pay': bas.pay, 'close': bas.close,
                 'work': bas.work, 'worktime': bas.worktime})
    print(list)
    return jsonify({'code': 200, 'list': list})


@classidy_blue.route("/gettypes")
def gettypes():
    type1 = types.query.all()
    list = []
    mlist = []
    for i in type1:
        if i.pid == 0:
            if i.id not in mlist:
                list.append({'id': i.id, 'name': i.name, 'son': []})
                mlist.append([i.id])

    for j in type1:
        for index,p in enumerate(list):
            if j.pid == p['id']:
                list[index]['son'].append({'id': j.id, 'name': j.name, 'pid': j.pid, 'sons': []})
    for x in type1:
        for index,p in enumerate(list):
            aa = list[index]['son']
            for indexs,t in enumerate(aa):
                if x.pid == t['id']:
                    aa[indexs]['sons'].append({'id': x.id, 'tname': x.name})
    print(list)
    return jsonify({'code': 200, 'list': list})


# 无限级分类
# @classidy_blue.route('/gettypes')
# def gettypes():
#     type1 = types.query.all()
#     list1=[]
#     rlist = []
#     dict = {}
#     for i in type1:
#         list1.append({'id':i.id,'name':i.name,'pid':i.pid})
#     for i in list1:
#         k = i['id']
#         dict[k] =i
#
#     for j in list1:
#         pid = j['pid']
#         if pid == 0:
#             rlist.append(j)
#         else:
#             if 'son' not in dict[pid]:
#                 dict[pid]['son']=[]
#             dict[pid]['son'].append(j)
#     print(rlist)
#     return jsonify({'code':200,'list':rlist})


# 雪花算法
# 导包雪花算法  import snowflake.client
def create_order(tablename, count):
    # 生成唯一id
    code = snowflake.client.get_guid()
    # 用redis解决时钟回拨，根据key查询上一次存入的结果，和当前生成的对比，如果当前小于redis中存储的，说明发生时钟回拨
    value = r.str_get(tablename)
    if value:
        if int(code) < int(value):
            create_order(tablename, code)
    r.str_add(tablename, code)
    r.list_push('projectkey', code)
    number = hash(code) % int(count)
    print(number)
    if number == 0:
        return tablename, code
    else:
        return tablename + str(number), code

def ontim_time(tablename, count):
    code = snowflake.client.get_guid()
    value = r.str_get(tablename)
    if value:
        if int(code) < int(value):
            create_order(tablename, code)
    r.str_add(tablename, code)
    r.list_push('ontimekey', code)
    number = hash(code) % int(count)
    if number == 0:
        return tablename, code
    else:
        return tablename + str(number), code


# 发布项目
@classidy_blue.route("/getproject", methods=['POST'])
def getproject():
    data = json.loads(request.data)

    name = data['name']
    print('_____________', name)
    title = data['title']
    descs = data['descs']
    types = data['type']
    money = data['budget']
    mobile = data['mobile']
    trade = data['trade']
    hire = data['hire']
    daily = data['daily']
    money1 = data['money']
    if name == '按项目付费':
        tablename, code = create_order('project', 3)
        print(tablename,code)
        # 转换成表名
        aa = globals().get(f'{tablename}')
        pro = aa(name=name, title=title, descs=descs, type=types, money=money, mobile=mobile, trade=trade,code=code)
        db.session.add(pro)
        db.session.commit()
        return jsonify({'code': 200, 'msg': '发布成功'})
    if name == '按时收费':
        tablename, code = create_order('ontime', 3)
        print(tablename, code)
        # 转换成表名
        tablename = globals().get(f'{tablename}')
        ontim = tablename(name=name, title=title, descs=descs, type=types, hire=hire, mobile=mobile, trade=trade,daily=daily, money=money1, code=code)
        db.session.add(ontim)
        db.session.commit()
        return jsonify({'code': 200, 'msg': '发布成功'})
    return jsonify({'code': 400, 'msg': '发布失败'})

# 查看发布项目信息  分页展示
@classidy_blue.route("/getprojectall")
def getprojectall():
    page = request.args.get('page')
    page_size = request.args.get('page_size')
    start = (int(page)-1) * int(page_size)
    q1 = db.session.query(project).filter(project.status == 0)
    q2 = db.session.query(project1).filter(project1.status == 0)
    q3 = db.session.query(project2).filter(project2.status == 0)
    q4 = db.session.query(ontime).filter(ontime.status == 0)
    q5 = db.session.query(ontime1).filter(ontime1.status == 0)
    q6 = db.session.query(ontime2).filter(ontime2.status == 0)
    ontimes = q4.union(q5).union(q6).offset(start).limit(page_size).all()
    print('AaAAA',ontimes)
    dict1 = []  # 按时计费
    for i in ontimes:
        dict1.append({
            'code': str(i.code),
            'name': i.name,
            'title': i.title,
            'descs': i.descs,
            'type': i.type,
            'mobile': i.mobile,
            'trade': i.trade,
            'money': i.money,
            'status': i.status,
            'userid': i.userid,
            'hire': i.hire,
            'daily': i.daily,
            'create_time': str(i.create_time),
            'update_time': str(i.update_time)
        })
    print('dict1', dict1)
    # union连接 offset起始页 limit每页去三条
    ret = q1.union(q2).union(q3).offset(start).limit(page_size).all()  # 数据重复，只留一条
    print(ret)
    # aa = ret.query.count()
    ret1 = q1.union(q2).union(q3).count()
    print(ret1)
    # print('ret1',ret1)
    # print(page_size)
    # aa = math.ceil(int(ret1)/int(page_size))
    # print('aa',aa)
    # print('aa',ret1)
    list = []  # 按项目计费
    for i in ret:
        list.append({
            'code': str(i.code),
            'name': i.name,
            'title': i.title,
            'descs': i.descs,
            'type': i.type,
            'money': i.money,
            'mobile': i.mobile,
            'trade': i.trade,
            'status': i.status,
            'userid': i.userid,
            'create_time': str(i.create_time),
            'update_time': str(i.update_time)
        })
    print(list)
    alllist = []  # 全部数据
    for i in list:
        alllist.append(i)
    for j in dict1:
        alllist.append(j)
    print('alllist', alllist)
    return jsonify({'code': 200, 'prolist': list, 'tcount': ret1, 'all': alllist, 'onlist': dict1})



@classidy_blue.route("/label_index")
def search():
    input = request.args.get('title')
    lst = []
    res = project.query.filter(project.title.ilike(f"%{input}%")).all()
    if res:
        lst.append(res)
    ress = project1.query.filter(project1.title.ilike(f"%{input}%")).all()
    if ress:
        lst.append(ress)
    resa = project2.query.filter(project2.title.ilike(f"%{input}%")).all()
    if resa:
        lst.append(resa)
    new_list = [j for i in lst for j in i]
    print(new_list)
    list = []
    if new_list:
        for s in new_list:
            list.append({
                'code': str(s.code),
                'name': s.name,
                'title': s.title,
                'descs': s.descs,
                'type': s.type,
                'money': s.money,
                'mobile': s.mobile,
                'trade': s.trade,
                'status': s.status,
                'userid': s.userid,
                'create_time': str(s.create_time),
                'update_time': str(s.update_time)
            })
            return jsonify({
                'code': 200,
                'msg': 'ok',
                'data': list
            })
        else:
            return jsonify({
                'code': 400,
                'msg': '数据不存在'
            })


































